Did the ==
operator look at the contents of the objects when the if
statement executed?
No. It only looked at the two reference variables.
They each held different references,
so the ==
evaluated to false.
Here is another example program:
class egString5 { public static void main ( String[] args ) { String strA; // reference to the object String strB; // another reference to the object strA = new String( "The Gingham Dog" ); // Create the only object. // Save its reference in strA. System.out.println( strA ); strB = strA; // Copy the reference to strB. System.out.println( strB ); if ( strA == strB ) System.out.println( "Same info in each reference variable." ); } } |
When this program runs,
only one object is created (by the new
).
The unique reference to the object is put into strA
.
The assignment operator in the statement
strB = strA; // Copy the reference to strB.
copies the information that is in strA
to strB
.
It
does not make a copy of the object!
Or, saying nearly the same thing: making a copy of a reference to an object
does not make a copy of the object!
Since the same information is stored in strA
as in strB
,
either variable leads to the same object.
This is somewhat like giving your phone number to several people:
each copy of your phone number is a reference to you, but there is only one you.
The program will output:
The Gingham Dog The Gingham Dog Same info in each reference variable.